//
//  MenusViewController.m
//  Menu
//
//  Created by mc on 16/4/15.
//  Copyright © 2016年 xmj. All rights reserved.
//

#import "MenusViewController.h"
#import "AFNetworking.h"
#import "MJExtension.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#import "Menus.h"
#import "MenusCell.h"
#import "MenusHeadView.h"
//#import "View+MASAdditions.h"
#import "SearchMenusVC.h"




@interface MenusViewController () <UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *menus;
@property (assign, nonatomic) NSInteger page;
@property (nonatomic, assign) BOOL isHasData;
//@property (nonatomic, assign) CGFloat cellHeight;
@property (strong, nonatomic) MenusHeadView *menusHeadView;

@end

@implementation MenusViewController

static NSString * const REQUESTURL = @"http://apis.haoservice.com/lifeservice/cook/query?";


- (UITableView*)tableView

{
    if(_tableView==nil) {
        _tableView= [[UITableView alloc]initWithFrame:CGRectMake(0, 35, self.view.bounds.size.width, self.view.bounds.size.height-35) style:UITableViewStyleGrouped];
       // self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(100, 0, 0, 0);
        //_tableView.contentInset =  (0 ,50);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        __weak __typeof(self) weakSelf = self;
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [weakSelf loadData];
        }];
        
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.page = 0;
            
            [weakSelf loadData];
        }];
        // 马上进入刷新状态
        //[self.tableView.mj_header beginRefreshing];
    }
    return _tableView;
}


- (void)viewWillAppear:(BOOL)animated{
    
    if (_isHasData == NO) {
        [self loadData];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
   self.view.backgroundColor = [UIColor whiteColor];

    self.menusHeadView =  [[[NSBundle mainBundle] loadNibNamed:@"MenusHeadView" owner:nil options:nil]lastObject];
    self.menusHeadView.frame = CGRectMake(0, 0, self.view.bounds.size.width, 35);
    [self.view addSubview:self.menusHeadView];
    [self.view addSubview:self.tableView];
    // self.tableView.estimatedRowHeight = 300;
    
    UIBarButtonItem *rightBtn =[ [UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchMenus)];
    self.navigationItem.rightBarButtonItem = rightBtn;
    //>ios8
   // self.tableView.rowHeight = UITableViewAutomaticDimension;
  
    [self.menusHeadView.barbecueButton addTarget:self action:@selector(clickHeadButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.menusHeadView.masterDishButton addTarget:self action:@selector(clickHeadButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.menusHeadView.steamTasteButton addTarget:self action:@selector(clickHeadButton:) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)searchMenus{
        SearchMenusVC *searchMenusVC = [[SearchMenusVC alloc] init];
        self.hidesBottomBarWhenPushed=YES;
        [self.navigationItem setBackBarButtonItem:[[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil]];
    
        [self.navigationController pushViewController: searchMenusVC animated: YES];
        self.hidesBottomBarWhenPushed=NO;
}
- (void)clickHeadButton:(UIButton *)btn {
    
    [self.menusHeadView changeBtnColor:btn];
    __weak __typeof(self) weakSelf = self;
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = btn.tag;
        [weakSelf loadData];
    }];
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
}


- (void)loadData{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = NSLocalizedString(@"Loading...", @"HUD loading title");
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"menu"] = @"番茄";
    _page = self.page++;
    params[@"pn"] = [NSString stringWithFormat:@"%ld",(long)self.page++];
    NSInteger rn = 4 * _page;
    params[@"pn"] =@"1";
    params[@"rn"] = [NSString stringWithFormat:@"%ld",(long)rn];
    params[@"key"] = @"3c286dc4f120495199b4503dbb52b835";
    __weak typeof(self) weakSelf = self;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
    
    [manager GET:REQUESTURL parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        // 利用MJExtension框架进行字典转模型
        weakSelf.menus = [Menus mj_objectArrayWithKeyValuesArray:responseObject[@"result"]];
        // 刷新数据（若不刷新数据会显示不出）
        [weakSelf.tableView reloadData];
        self.isHasData = YES;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"" message:[error localizedDescription] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:nil];
        [alertView addAction:cancelAction];
        [self presentViewController:alertView animated:(YES) completion:^{
            
        }];
        
    }];
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.menus.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MenusCell *cell = [MenusCell menusCellWithTableView:self.tableView];
    cell.menus = self.menus[indexPath.section];
    [cell layoutIfNeeded];
    //[cell setNeedsUpdateConstraints];
    //[cell updateConstraintsIfNeeded];
   // self.cellHeight = cell.cellHeight;
    return cell;
}
     


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //MenusCell *cell = [MenusCell menusCellWithTableView:self.tableView];
    //cell.menus = self.menus[indexPath.section];
   // if (cell.cellHeight <= 0) {
        //使用systemLayoutSizeFittingSize获取高度
      //  cell.cellHeight = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height + 14;
   // }
     //>ios7
    //return UITableViewAutomaticDimension;
   
    Menus *menus = self.menus[indexPath.section];;
    return [MenusCell height:menus];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 跳转到详情.
//    SelectCoursesDetailVC * detailVC = [[SelectCoursesDetailVC alloc] init];
//    detailVC.selectCourse = self.selectCourses[indexPath.row];
//    self.hidesBottomBarWhenPushed=YES;
//    [self.navigationItem setBackBarButtonItem:[[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil]];
//    
//    [self.navigationController pushViewController: detailVC animated: YES];
//    self.hidesBottomBarWhenPushed=NO;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

@end
